package xuegao.study.mall.rbac.util;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.context.ApplicationContext;
import xuegao.study.mall.common.model.ums.UmsDepartment;
import xuegao.study.mall.rbac.service.UmsDepartmentService;

import java.util.ArrayList;
import java.util.List;

public class DepartmentDataListener extends AnalysisEventListener<UmsDepartmentExcelInfo> {

    private static final Logger LOGGER = LoggerFactory.getLogger(DepartmentDataListener.class);

    private List<UmsDepartmentExcelInfo> list;

    private ApplicationContext context;

    public DepartmentDataListener(ApplicationContext context) {
        this.context = context;
    }

    @Override
    public void invoke(UmsDepartmentExcelInfo umsDepartmentExcelInfo, AnalysisContext analysisContext) {
        if (list == null) {
            list = new ArrayList<>();
        }
        list.add(umsDepartmentExcelInfo);
        LOGGER.info("读取到一条数据！");
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        LOGGER.info("所有数据解析完成！");
        LOGGER.info("{}", list);
        UmsDepartmentService umsDepartmentService = context.getBean(UmsDepartmentService.class);
        List<UmsDepartment> dataList = new ArrayList<>();
        for (UmsDepartmentExcelInfo info : list) {
            UmsDepartment dep = new UmsDepartment();
            BeanUtils.copyProperties(info, dep);
            dataList.add(dep);
        }
        umsDepartmentService.importDep(dataList);
        LOGGER.info("导入完成");
    }
}
